﻿using Authentication.Model.Interface;
using Authentication.Model.Model;
using Common.Contract;
using Common.Contract.Authentication;
using Common.Contract.Authentication.Identifier;
using Common.Contract.Authentication.Request;
using Common.Service.Command;
using Common.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Authentication.ServiceCommand
{
    public class DeleteUserRolesServiceCommand : ProviderServiceCommand<IUserRoleProvider, DeleteUserRolesRequest, ResponseRecord>
    {
        public DeleteUserRolesServiceCommand(IUserRoleProvider providers) : base(providers) { }
        protected override void Validate(DeleteUserRolesRequest request)
        {
            if (request == null) throw new ArgumentNullException("request");
            if (!request.Header.ApplicationKey.HasValue || request.Header.ApplicationKey == Guid.Empty)
            {
                throw new ArgumentException("ApplicationKey must be set", "request");
            }
            if (request.Record == null || request.Record.Count == 0)
            {
                throw new ArgumentException("Record must be set", "request");
            }
        }

        protected override bool OnExecute(ResponseRecord response)
        {
            var applicationKey = Request.Header.ApplicationKey.Value;
            bool result = true;
            foreach (var groupRole in Request.Record)
            {
                groupRole.Active = false;
                int ruleId = -1;
                if (RoleIdentifier.IsValid(groupRole.RoleIdentifier))
                    ruleId = new RoleIdentifier(groupRole.RoleIdentifier).PersistableID;

                ApplicationAccountRule item = new ApplicationAccountRule
                {
                    ApplicationKey = groupRole.ApplicationKey.ToString().ToUpper(),
                    UserName = groupRole.UserName,
                    ObjectId = groupRole.ObjectIdentifier,
                    RuleId = ruleId,
                    Active = groupRole.Active.Value.ToBooleanString()
                };
                var roleId = Providers.Delete(item);
                if (!roleId) result = false;
            }

            return result;
        }
    }
}
